<template>
  <m-container class="start-do">
    <out-work-top-cell :info="info" />
    <view class="top-box">
      <m-radio-group inline :value="currentIndex">
        <m-radio-button :label="index" v-for="(item, index) in list" :key="item.outWorkId">
          <text class="title">{{ item.stackNo + '-' + item.levelNo + '-' + item.locationNo }}</text>
          <text :style="{ color: outTaskStatusMap[item.status].color }">{{ outTaskStatusMap[item.status].text }}</text>
        </m-radio-button>
      </m-radio-group>
    </view>

    <m-cell-group weight="label" size="sm" :border="false">
      <view class="box">
        <view class="df aic jcsb">
          <m-tag>任务{{ currentIndex + 1 }}：{{ modal.outWorkId }}</m-tag>
          <text style="padding-right: 20rpx; color: #8e949b; font-size: 32rpx" :class="{ active: true }">
            {{ getTotal }}/{{ modal.totalPickNumber }}
          </text>
        </view>
        <view class="df aic jcsb" style="margin: 0 0 20rpx">
          <view class="item">
            <text class="title">当前托盘</text>
            <text>{{ modal.isScanCode || modal.status === 2 ? modal.palletCode : '等待扫码中...' }}</text>
          </view>
        </view>

        <view class="over" v-for="(item, index) in modal.imsStockOutWorkDetailList" :key="index">
          <view class="item df aic" style="background-color: #f2f7fd; padding-bottom: 16rpx; margin-bottom: 20rpx">
            <image src="@/static/icon9.png" mode="scaleToFill" class="icon_box" />
            <view class="right">
              <view class="item">
                <text class="title">零件图号</text>
                <text>{{ item.partNo }}</text>
              </view>
              <view class="item">
                <text class="title">出库数量（个）</text>
                <text>{{ item.packageNumber }}</text>
              </view>
            </view>
          </view>
          <template v-if="modal.isScanCode || modal.status === 2">
            <template v-if="item.skuBarcodes.length">
              <in-work-code
                broder
                v-for="(it, index) in item.skuBarcodes"
                :modal="{ barcode: it.barcode }"
                :key="index"
                :status-type="outTaskCodeStatus[it.status].color || 'primary'"
                :status-txt="outTaskCodeStatus[it.status].text || '已出库'"
              />
            </template>
            <m-empty :margin-top="20" v-else tip="还没有开始扫描条码哦！" />
          </template>
        </view>

        <view style="margin: 40rpx 20rpx 0" v-if="modal.status !== 2" key="0">
          <m-button
            width="100%"
            shape="round"
            size="xl"
            plain
            background="#fff"
            @click="handleClickOver()"
            v-if="getTotal == modal.totalPickNumber"
          >
            拣货完成
          </m-button>

          <m-button
            v-else
            width="100%"
            shape="round"
            size="xl"
            plain
            background="#fff"
            :disabled="!modal.isScanCode"
            @click="handleClickConfirm"
          >
            扫码拣货
          </m-button>
        </view>

        <view style="margin: 40rpx 20rpx 0" v-else-if="modal.showBack" key="1">
          <m-button width="100%" shape="round" size="xl" plain @click="goOutWorkTaskOver"> 去回库 </m-button>
        </view>
      </view>
    </m-cell-group>

    <m-fixed>
      <m-button width="100%" size="xl" @click="handleClickOutWorkOver" v-if="getAllOver"> 已完成 </m-button>
      <m-button width="100%" size="xl" @click="handleClickConfirm" v-else :disabled="getDisabled">扫描托盘码</m-button>
    </m-fixed>
  </m-container>
</template>

<script>
const barcodeModel = uni.requireNativePlugin('iData-BarcodePlugin-BarcodeModule')
const globalEvent = uni.requireNativePlugin('globalEvent')
import { outTaskStatusMap, outTaskCodeStatus } from '@/utils/constant'
import deepClone from '@/utils/deep-clone'
import { router } from '@/router'
import { showModal } from '@/hooks'
import { minCache } from '@/utils/min-cache'
import {
  getOutOrder,
  imsStockOutWork,
  checkSkuIsStandard,
  finishOutWorkPick,
  updateOutOrder,
  completedOutOrder,
  storageLocationDetails,
} from '@/api/modules/out-work'

export default {
  data() {
    return {
      info: {},
      outTaskStatusMap,
      outTaskCodeStatus,
      type: 1,
      currentIndex: 0,
      list: [],
      options: {},
    }
  },
  computed: {
    modal() {
      return this.list[this.currentIndex] || { imsStockOutWorkDetailList: [] }
    },
    getDisabled() {
      const { isScanCode, status } = this.modal
      return status === 2 ? false : isScanCode
    },
    getTotal() {
      return this.modal.imsStockOutWorkDetailList.reduce((pre, cur) => {
        pre += cur.skuBarcodes.length
        return pre
      }, 0)
    },
    getAllOver() {
      return this.list.every((item) => item.status === 2) && this.status !== 2
    },
  },
  onUnload() {
    minCache.delete('outOrderId')
    this.info = null
    barcodeModel.closeScan()
  },
  async onLoad(options) {
    this.options = options
    barcodeModel.initScan()
    globalEvent.addEventListener('iDataBarcodeEvent', this.handleScanCode)
  },
  onShow() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const { id } = this.options
      const { data } = await getOutOrder(id)
      const { rows } = await imsStockOutWork({ outOrderId: id, barCodeStatus: 6 })
      this.info = data

      this.list = rows.map((item) => ({
        ...item,
        isScanCode: false,
        totalPickNumber: item.totalPickNumber || 1,
        imsStockOutWorkDetailList: item.imsStockOutWorkDetailList.map((it) => {
          if (item.status === 2) {
            it.skuBarcodes = it.palletCodeSkuList.map((i) => ({ ...i, barcode: i.skuBarcode }))
          } else {
            it.skuBarcodes = item.skuBarcodes || []
          }
          return it
        }),
      }))

      return await this.fetchStorageLocationDetails()
    },
    async handleScanCode({ barcode }) {
      if (
        this.$Router.currentRoute.name !== 'OutWorkStartDo' ||
        this.info === null ||
        +this.$Router.currentRoute.query.id !== this.info.outOrderId ||
        +minCache.get('outOrderId') !== this.info.outOrderId
      ) {
        return
      }

      // 处理扫托盘任务
      if (barcode.startsWith('WMS-P-')) {
        const { rows } = await imsStockOutWork({ outOrderId: this.info.outOrderId, palletCode: barcode })
        if (rows.length === 0) {
          uni.showToast({
            title: '非本次任务托盘码',
            icon: 'none',
          })
          return
        }

        const index = this.list.findIndex((item) => item.outWorkId === rows[0].outWorkId)
        if (index === -1) {
          uni.showToast({
            title: '非本次任务托盘码',
            icon: 'none',
          })
          return
        }
        this.currentIndex = index
        this.list[index].isScanCode = true
        return
      }

      if (!this.modal.isScanCode) {
        uni.showToast({
          title: '请先扫托盘码',
          icon: 'none',
        })
        return
      }

      let { palletCode, totalPickNumber, imsStockOutWorkDetailList } = this.modal
      const index = imsStockOutWorkDetailList.findIndex((item) => barcode.includes(item.partNo))
      if (index === -1) {
        uni.showToast({
          title: '条码和零件图号不匹配',
          icon: 'none',
        })
        return
      }

      const { skuBarcodes, notRoundOutNumber, roundOutNumber } = imsStockOutWorkDetailList[index]
      const array = skuBarcodes.map((item) => item.barcode)
      if (array.includes(barcode)) {
        uni.showToast({
          title: '该码已存在',
          icon: 'none',
        })
        return
      }

      // 处理扫零件图号任务
      const bool = await checkSkuIsStandard({
        skuBarcode: barcode,
        palletCode,
        status: 4,
      })
      const data = { barcode, roundOut: bool ? 1 : 0, status: 4 }
      const arr = skuBarcodes.filter((item) => item.roundOut === (bool ? 1 : 0))

      if (arr.length < (bool ? roundOutNumber : notRoundOutNumber) && skuBarcodes.length < +totalPickNumber) {
        skuBarcodes.unshift(data)
      } else {
        showModal({
          title: '温馨提示',
          content: bool ? '当前的扫码已超出该项任务的整出数量了' : '当前的扫码已超出该项任务的零出数量了',
          confirmText: '我知道了',
          slot: true,
        })

        return
      }

      imsStockOutWorkDetailList[index].skuBarcodes = skuBarcodes
    },
    async handleClickOver() {
      const modal = deepClone(this.modal)
      modal.imsStockOutWorkDetailList = modal.imsStockOutWorkDetailList.map((item) => ({
        ...item,
        skuBarcodes: item.skuBarcodes.map((item) => item.barcode),
      }))
      await finishOutWorkPick(modal)

      const data = await this.fetchData()
      if (data.length) {
        this.goOutWorkTaskOver()
      }
    },
    goOutWorkTaskOver() {
      const { outOrderId, outWorkId, palletCode } = this.modal
      router.push({
        name: 'OutWorkTaskOver',
        params: {
          outOrderId,
          outWorkId,
          palletCode,
        },
      })
    },
    async fetchStorageLocationDetails() {
      if (this.modal.palletCode) {
        const { data } = await storageLocationDetails({
          palletCode: this.modal.palletCode,
        })

        this.$set(this.list[this.currentIndex], 'showBack', !!data.length)
        return data
      } else {
        return []
      }
    },
    handleClickOutWorkOver() {
      showModal({
        title: '已完成提示',
        content: '请问您确认是否完成了本次出库单内所有的出库任务了吗?',
        showCancelButton: true,
        slot: true,
        confirm: async () => {
          const { outOrderId } = this.info
          await completedOutOrder({
            outOrderId,
            palletCode: this.list.map((item) => item.palletCode).join(','),
          })
          uni.showToast({
            title: '出库单已完成',
            icon: 'none',
          })

          router.back()
        },
      })
    },
    handleClickConfirm() {
      barcodeModel.scanStart(() => {
        console.log(7)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.start-do {
  .top-box {
    padding: 20rpx 30rpx 0;
    color: #748da7;
    font-size: 24rpx;
    text-align: center;
    overflow: auto;
    .title {
      font-size: 32rpx;
      display: block;
      margin-bottom: 15rpx;
      font-weight: bold;
    }

    .radio {
      background: #fff;
      border-color: #d7dce0;
      border-radius: 12rpx;
      min-width: 186rpx;
      height: 108rpx;
      margin-bottom: 0;
      &--checked {
        border-color: #248dfa;
      }
    }
  }
  .box {
    padding: 20rpx 0 25rpx;
    .active {
      color: #248dfa !important;
    }
    .item {
      display: flex;
      color: #333;
      font-size: 30rpx;
      padding: 15rpx 20rpx 0rpx;
      flex: 1;
      .title {
        color: #748da7;
        width: 180rpx;
        font-size: 26rpx;
      }
    }
  }
  .over {
    max-height: 650rpx;
    overflow: auto;
    margin: 0 20rpx;
    .icon_box {
      width: 86rpx;
      height: 86rpx;
      margin-right: 10rpx;
    }
  }

  ::v-deep {
    .radio {
      background: #fff;
      padding: 10rpx 20rpx;
      &--checked {
        color: #248dfa;
      }
    }
  }
}
</style>
